package com.john.booter.module.file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.john.booter.config.BooterSettings;

@RestController
@RequestMapping("/upload")
public class UploadCtrl {
	
	@Autowired
	private BooterSettings setting; 

	/**
	 * 单文件上传
	 * @param name
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/single", method = RequestMethod.POST)
	public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
			@RequestParam("file") MultipartFile file) {
		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();
				String fileUploadPath = setting.getFileUploadPath();
				String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
				String savePath = fileUploadPath + File.separator + name + suffix;
				
				BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
						new File(savePath)));
				stream.write(bytes);
				stream.close();
				return "You successfully uploaded " + name + " into " + name + "suffix!";
			} catch (Exception e) {
				return "You failed to upload " + name + " => " + e.getMessage();
			}
		} else {
			return "You failed to upload " + name + " because the file was empty.";
		}
	}

	/**
	 * 多文件上传
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/batch", method = RequestMethod.POST)
	public @ResponseBody String handleFileUpload(HttpServletRequest request) {
		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		String fileUploadPath = setting.getFileUploadPath();
		for (int i = 0; i < files.size(); ++i) {
			MultipartFile file = files.get(i);
			String name = file.getOriginalFilename();
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
					String savePath = fileUploadPath + File.separator + name + suffix;
					BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(savePath)));
					stream.write(bytes);
					stream.close();
				} catch (Exception e) {
					return "You failed to upload " + name + " => " + e.getMessage();
				}
			} else {
				return "You failed to upload " + name + " because the file was empty.";
			}
		}
		return "upload successful";
	}

}
